const Favorite = require('../models/Favorite')
const {pagination} = require('../utils/utils')
const Article = require('../models/Article')
exports.postFavorite = async (req, res, next) => {
  const articleId = req.params.articleId
  console.log('articleId: ', articleId)
  const userId = req._id
  console.log('userId: ', userId)
  try {
    const favoriteExists = await Favorite.findOne({
      userId,
      articleId,
    })
    console.log('favoriteExists: ', favoriteExists)
    if (favoriteExists) {
      // 如果收藏已存在，执行取消收藏逻辑
      await Favorite.deleteOne({_id: favoriteExists._id})
      await Article.updateOne({_id: articleId}, {$inc: {favorite_num: -1}})
      res.success({favorite: 0}, '取消收藏成功')
    } else {
      // 如果收藏不存在，执行收藏
      const newFavorite = new Favorite({
        userId,
        articleId,
      })
      await newFavorite.save()
      await Article.updateOne({_id: articleId}, {$inc: {favorite_num: 1}})
      res.success({favorite: 1}, '收藏成功')
    }
  } catch (error) {
    next(error)
  }
}

exports.getFavorites = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 10
  const userId = req.params.userId
  console.log('userId: ', userId)
  try {
    // 调用分页方法
    let paginateResult = await pagination({
      model: Favorite,
      select: '-createdAt',
      pageNumber,
      pageSize,
      query: {userId},
      populate:[
      {
        path: 'articleId', // 需要填充的评论字段
        select: '-comments  -date -author -category', // 选择要展示的字段
      },
      {
        path: "userId", // 需要填充的评论字段
        select: "nikname", // 选择要展示的字段
      }
    ],
    })

    console.log('paginateResult:',paginateResult)
    //过滤变成草稿的文章
    paginateResult.list=paginateResult.list.filter(item=>{
      return !item.articleId.is_draft
    })
    paginateResult.list = paginateResult.list.map(item => {
      console.log('item:',item)
      return {
        id: item.articleId._id,
        title: item.articleId.title,
        cover_img:item.articleId.cover_img,
        hit_num:item.articleId.hit_num,
        like_num:item.articleId.like_num,
        comment_num:item.articleId.comment_num,
        intro:item.articleId.intro,
        nikname:item.userId.nikname
      }
    })
    /*
    * "hit_num": 223,
                    "like_num": 3,
                    "favorite_num": 3,
                    "comment_num": 0,
                    "cover_img": "http://localhost:3000/img/article-cover.jpg",
                    "intro": "当各种框架以及复杂的 JS 知识开始充斥着我们的工作环境时。谁还能够记得，以 CSS 来构建更加良好的用户体验，也是前端的一个重要组成部分。",
    * */
    res.success(paginateResult, '我的收藏文章列表查询成功')
  } catch (err) {
    console.log(err)
    next(err)
  }
}
